package org.mq.mymq.broker.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.util.internal.StringUtil;
import org.mq.mymq.broker.cache.CommonCache;
import org.mq.mymq.broker.model.ConsumeQueueOffsetModel;
import org.mq.mymq.broker.utils.FileContentUtil;
import org.mq.mymq.common.constants.BrokerConstants;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ConsumerQueueOffsetLoader
 * @Description 加载消费者队列消费信息
 * @Author jiarong_ye
 * @Date 2025/6/16 18:35
 * @Version 1.0
 */
public class ConsumeQueueOffsetLoader {
    private String filePath;

    public void loadProperties() {
        String basePath = CommonCache.getGlobalProperties().getMyMqHome();
        if (StringUtil.isNullOrEmpty(basePath)) {
            throw new IllegalArgumentException("MY_MQ_HOME is invalid");
        }
        filePath = basePath + "/config/consumequeue-offset.json";
        String fileContent = FileContentUtil.readFromFile(filePath);
        ConsumeQueueOffsetModel consumeQueueOffsetModel = JSON.parseObject(fileContent, ConsumeQueueOffsetModel.class);
        CommonCache.setConsumeQueueOffsetModel(consumeQueueOffsetModel);;
    }

    /**
     * 开启一个异步任务：刷新内存到磁盘
     */
    public void startRefreshConsumerQueueOffsetTask() {
        // 开启异步线程，每15秒将内存中的配置刷新到磁盘
        CommonThreadPoolConfig.refreshConsumerQueueOffsetExecutor.execute(new Runnable() {
            public void run() {
                do {
                    try {
                        TimeUnit.SECONDS.sleep(BrokerConstants.DEFAULT_REFRESH_CONSUMER_OFFSET_TIMESTEP);
                        ConsumeQueueOffsetModel consumeQueueOffsetModel = CommonCache.getConsumeQueueOffsetModel();
                        FileContentUtil.overWriteToFile(filePath, JSON.toJSONString(consumeQueueOffsetModel, JSONWriter.Feature.PrettyFormat));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } while(true);
            }
        });
    }
}
